<template>
    <div id="container">
        <div id="login-head">
            <div class="logo">
                <img src="../assets/img/logo.png" alt="logo" style="max-width: 100px; height: auto;">
            </div>
            <div class="title">
                <div class="h1">社区养老服务管理系统</div>
            </div>
        </div>

        <div id="login-body">
            <!-- <el-carousel indicator-position="outside">
                <el-carousel-item v-for="item in carouselImg" :key="item"> -->
            <img :src="login5" alt="" class="carouselImg">
            <!-- </el-carousel-item>
            </el-carousel> -->
            <div class="loginwin">
                <el-card class="box-card">
                    <template #header>
                        <div class="card-header">
                            <h1 class="align-center">欢迎使用</h1>
                        </div>
                    </template>
                    <div class="loginform">
                        <el-form :model="ruleForm" ref="ruleFormRef" class="demo-ruleForm" :size="formSize" status-icon
                            :rules="rules">
                            <el-form-item prop="loginName">
                                <el-input v-model="ruleForm.loginName" placeholder="请输入用户名或手机号" :prefix-icon="Avatar" />
                            </el-form-item>
                            <el-form-item prop="checkPass">
                                <el-input v-model="ruleForm.password" placeholder="请输入密码" :prefix-icon="Lock"
                                    type="password" show-password />
                            </el-form-item>
                            <el-form-item prop="code">
                                <!-- <template #label>
                                    <span style="font-size: 16px;color: orange">验证码</span>
                                </template> -->
                                <el-input v-model.trim="ruleForm.code" placeholder="请输入验证码" :prefix-icon="Bell"
                                    autocomplete="off"></el-input>
                            </el-form-item>
                            <el-image :src="imgUrl" class="img-code" alt="加载失败" @click="resetImg" />
                            <el-form-item>
                                <div class="btn">
                                    <el-button type="primary" @click="submitForm(ruleFormRef)" :icon="Promotion">
                                        立即登录
                                    </el-button>
                                    <el-button link type="primary" @click="register"
                                        style="margin-left: 20px;">注册</el-button>
                                </div>
                            </el-form-item>
                        </el-form>
                    </div>
                </el-card>
            </div>
        </div>
        <div id="footer">
            <!-- <img src="../assets/img/footer.png" alt="" class="imgFooter"> -->
        </div>
    </div>
</template>

<script setup>
import { Avatar, Lock, Promotion, Bell } from '@element-plus/icons-vue'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus';
import { reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router';
import $axios from '../utils/axios'
import login5 from '@/assets/img/login5.jpg';

let key = new Date().getTime()
console.log(key);
const imgUrl = ref('')
imgUrl.value = "http://localhost:8083/user/getVerificationCode/" + key

const resetImg = () => {
    key = new Date().getTime()
    imgUrl.value = "http://localhost:8083/user/getVerificationCode/" + key
}

const carouselImg = [
    { url: login5 },
    //     { url: ocean },
    //     { url: tree }
]

onMounted(() => {
    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    setTimeout(() => {
        loading.close()
    }, 1000);
    // funcCode();
});

const router = useRouter()

const formSize = ref('default')

//在vue3中通过ref属性获得对象的方法
const ruleFormRef = ref()
const ruleForm = ref({
    // loginName: 'admin',
    // password: '111111'
})

/**
 *定义验证规则
 * @param {*} rule
 * @param {*} value 当前文本框返回的值
 * @param {*} callback 回调函数，通知Form验证结果
 * 返回Error失败  callback(new Error('Please input the password'))
 * new Error( msg--  提示信息 )
 * 返回null 成功  callback()
 */
const validatePass2 = (rule, value, callback) => {
    if (
        !ruleForm.value.password ||
        ruleForm.value.password.length == 0
    )
        callback(new Error('请输入密码'))
    // console.log(ruleForm.value.password)
    if (ruleForm.value.password === '')
        callback(new Error('请输入密码'))
    else callback()
}

const rules = reactive({
    loginName: [
        {
            required: true, //必填规格
            message: '请输入用户名或手机号', //违反规则提示的信息
            trigger: 'blur' //失去焦点时触发
        },
        {
            min: 5,
            max: 11,
            message: '5-11个字符',
            trigger: 'blur'
        }
    ],
    password: [
        {
            required: true, //必填规格
            message: '请输入密码', //违反规则提示的信息
            trigger: 'blur' //失去焦点时触发
        },
        {
            min: 6,
            max: 18,
            message: '6-18个字符',
            trigger: 'blur'
        }
    ],
    checkPass: [
        { validator: validatePass2, trigger: 'blur' }
    ],
    code: [
        {
            required: true,
            message: '请输入验证码',
            trigger: 'blur'
        }
    ]
})

const submitForm = async (formEl) => {
    if (!formEl) return
    // 在提交数据之前对所有的数据进行一次统一的验证
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            // 所以的数据已经通过验证
            console.log(ruleForm.value)
            console.log(key);
            const path = '/user/login/' + key
            //  发送登录请求
            try {
                const res = await $axios.post(path, ruleForm.value, {
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                    }
                })
                
                console.log('登录响应:', res.data)
                const response = res.data  // 直接使用 res.data

                if (response.code === 200) {
                    // 登录成功提示
                    ElMessage({
                        message: '登录成功',
                        type: 'success',
                        duration: 2000
                    })

                    // 存储用户信息
                    const user = response.result.user
                    const token = response.result.token
                    localStorage.setItem('user', JSON.stringify(user))
                    localStorage.setItem('token', token)
                    localStorage.setItem('roleId', user.roleId + '')
                    localStorage.setItem('id', user.id + '')

                    // 设置 axios 请求头
                    $axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
                    $axios.defaults.headers.common['token'] = token

                    // 根据角色跳转到不同页面
                    const roleId = parseInt(user.roleId)
                    console.log('用户角色:', roleId)

                    switch (roleId) {
                        case 4: // 普通用户
                            router.push('/front/home/FrontHomeView')
                            break
                        case 3: // 医护人员
                            router.push('/home/HealthOrderView')
                            break
                        case 2: // 社区工作者
                            router.push('/home/ActivityMenageView')
                            break
                        case 1: // 管理员
                            router.push('/home/IndexView')
                            break
                        default:
                            console.error('未知的用户角色:', roleId)
                            ElMessage.error(`角色ID ${roleId} 未定义对应的页面`)
                            // 清除登录信息
                            localStorage.removeItem('user')
                            localStorage.removeItem('token')
                            localStorage.removeItem('roleId')
                            localStorage.removeItem('id')
                            router.push('/login')
                            break
                    }
                } else if (response.code === 102) {
                    // 账号审核中
                    ElMessageBox.alert(
                        '您的账号正在审核中\n\n' +
                        '• 审核预计需要1-2个工作日\n' +
                        '• 审核结果将通过短信通知您\n' +
                        '• 审核通过后即可正常登录\n\n' +
                        '如有疑问，请联系社区工作人员',
                        '温馨提示',
                        {
                            confirmButtonText: '我知道了',
                            type: 'warning'
                        }
                    )
                } else if (response.code === 103) {
                    // 账号审核被拒绝
                    ElMessageBox.alert(
                        '很抱歉，您的注册申请未通过审核\n\n' +
                        '原因：' + (response.msg || '不符合注册条件') + '\n\n' +
                        '如有疑问，请联系社区工作人员',
                        '审核未通过',
                        {
                            confirmButtonText: '确定',
                            type: 'error'
                        }
                    )
                } else if (response.code === 101) {
                    ElMessage.error('用户名或密码错误')
                } else if (response.code === 108) {
                    ElMessage.error("验证码错误!")
                    imgUrl.value = "http://localhost:8083/user/getVerificationCode?key=" + new Date()
                } else {
                    ElMessage.error(response.msg || '登录失败，请稍后重试')
                }
            } catch (error) {
                console.error('登录请求失败:', error)
                ElMessage.error('系统错误，请稍后重试')
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}

const register = () => {
    router.push('/register')
}

// const resetForm = (formEl) => {
//   formEl.resetFields()
//   if (!formEl) return
//   formEl.resetFields()
// }
</script>

<style lang="scss" scoped>
#container {
    display: flex;
    width: 100%;
    height: 80%;

    #login-head {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 10%;

        .logo {
            position: absolute;
            top: 45%;
            // left: 200px;
            margin-left: 13%;
            transform: translate(-50%, -50%);

            img {
                width: 70%;
                height: 70%;
                margin-top: 10px;
            }
        }

        .title {
            position: relative;
            display: flex;
            // left: 230px;
            align-items: center;
            height: 100%;
            // width: 100%;
            margin-left: 15%;
            font-size: 25px;
            color: black;
        }
    }

    #login-body {
        position: absolute;
        margin-top: 75px;
        height: 90%;
        width: 100%;
        background-color: rgb(245, 245, 245);

        .carouselImg {
            border: 1px solid #ccc;
            border-radius: 4px;
            overflow: hidden;
            width: 100%;
            height: 100%;
        }

        .loginwin {
            width: 25%;
            height: 55%;
            position: absolute;
            left: 30%;
            top: 50%;
            transform: translate(-50%, -50%);
            border-radius: 10px;



            .box-card {
                width: 100%;
                height: 100%;
                margin: 0 auto;
                float: inline-start;
                text-align: center;
                border-radius: 15px;
                background: #F0F8FF;
                opacity: 0.85;
                align-items: center;

                .card-header {
                    display: flex;

                    .align-center {
                        width: 100%;
                        font-size: 25px;
                        text-align: center;
                        color: #4682B4;
                    }
                }

                .loginform {
                    padding: 10px;

                    .img-code {
                        width: 50%;
                        height: 50%;
                    }
                }
            }
        }
    }

    #footer {
        position: absolute;
        margin-top: 200px;
        bottom: 0;
        left: 0;
        width: 100%;
        height: 20%;

        .imgFooter {
            position: relative;
            margin-top: 50px;
            display: flex;
            width: 100%;
            height: 300%;
        }
    }
}
</style>